package c.a.md.androidvideo;

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import java.util.LinkedList;

public class RecordAndPlayActivity extends AppCompatActivity
{

    private TextView t1;

    private int minBufferSize;
    private byte[] recordInBuffer, playOutBuffer;

    private boolean isRecording;

    private AudioRecord recorder;
    private AudioTrack player;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_and_play);
        t1 = findViewById(R.id.vi);

        config();

    }

    @SuppressLint("ClickableViewAccessibility")
    private void config()
    {
        t1.setOnTouchListener(new View.OnTouchListener()
        {
            @Override
            public boolean onTouch(View v, MotionEvent e)
            {
                switch (e.getAction())
                {
                    case MotionEvent.ACTION_DOWN:
                        doStart();
                        return true;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        doStop();
                        break;
                }
                return false;
            }
        });
    }

    private void initAudioAndTrack()
    {
        //配置AudioRecord
        int audioSource = MediaRecorder.AudioSource.MIC;
        //所有android系统都支持
        int sampleRate = 44100;
        //单声道输入
        //PCM_16是所有android系统都支持的
        int audioFormat = AudioFormat.ENCODING_PCM_16BIT;
        //计算AudioRecord内部buffer最小
        minBufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, audioFormat);
        //buffer不能小于最低要求，也不能小于我们每次我们读取的大小。
        recorder = new AudioRecord(audioSource, sampleRate, AudioFormat.CHANNEL_IN_MONO, audioFormat, minBufferSize);
        recordInBuffer = new byte[minBufferSize];

        //音乐类型，扬声器播放
        int streamType = AudioManager.STREAM_MUSIC;
        //流模式
        int mode = AudioTrack.MODE_STREAM;

        //计算最小buffer大小
        int minTrackBufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, audioFormat);
        playOutBuffer = new byte[minTrackBufferSize];

        //构造AudioTrack  不能小于AudioTrack的最低要求，也不能小于我们每次读的大小
        player = new AudioTrack(streamType, sampleRate, AudioFormat.CHANNEL_OUT_MONO, audioFormat, minTrackBufferSize, mode);
    }

    private RecordThread recordThread;

    private void doStop()
    {
        if(recordThread != null)
            recordThread.jiji();
    }

    private void doStart()
    {
        initAudioAndTrack();
        isRecording = true;
        recordThread = new RecordThread();
        recordThread.start();
    }

    private class RecordThread extends Thread
    {

        byte[] bytes;

        @Override
        public void run()
        {
            if(recorder == null)
                return;
            try
            {
                recorder.startRecording();
                player.play();
                while (isRecording)
                {
                    int read = recorder.read(recordInBuffer, 0, minBufferSize);
                    bytes = new byte[read];
                    System.arraycopy(recordInBuffer, 0, bytes, 0, read);
                    player.write(bytes, 0, bytes.length);
                }
            }catch (Exception e)
            {

            }
        }

        public void jiji()
        {
            try
            {
                isRecording = false;

                player.stop();
                player.release();
                player = null;

                recorder.stop();
                recorder.release();
                recorder = null;
            }catch (Exception e)
            {
            }
        }
    }
}
